import type router from './router'
import { userInfo } from '@/store/userInfo'
import { upLine } from '@/socket/index'
const whiteRouters = ['/login', '/404', '/register']
// import axios from 'axios'
import { getUserInfo } from '@/api/users'
export default function (road: typeof router) {
  road.beforeEach((to, from, next) => {
    // 如果前往路由非白名单路由则验证token是否存在
    const token = localStorage.getItem('token');
    if (!whiteRouters.includes(to.path)) {
      // 如果没有token重定向到登录
      if (!token) {
        return next('/login')
      } else {
        getUserInfo().then(res => {
          userInfo.value = res.data; // 存储用户信息
          upLine(res.data.userId); // 通知服务器当前登录者的id
          next()
        }).catch(() => {
           next('/login');
        })
        return
      }
    }
    next()
  })
}
